<template>
  <div>
    <a-spin :spinning="loading">
      <div class="operate-page-content make-process-operate-container">
        <div class="header-search">
          <a-row :gutter="40" class="flex align-center">
            <a-col :span="5">
              {{$t('hangManage.makeNo')}}：
              <span class="text-gray1 ml-10 break-all">{{moInfo.moNo}} </span>
            </a-col>
            <a-col :span="5">
              {{$t('basicData.styleNo')}}：
              <span class="text-gray1 ml-10">{{moInfo.styleNo}} </span>
            </a-col>
            <a-col :span="5">
              {{$t('basicData.styleNa') }}：
              <span class="text-gray1 ml-10">{{moInfo.styleName}} </span>
            </a-col>
            <a-col :span="9" class="text-right">
              <a-select :placeholder="$t('other.selectVersion')" class="text-left" v-model:value="processVersionId" v-if="operateType != 'add'" :disabled="operateType == 'edit'" @change="()=> {getProcessDetails()}">
                <a-select-option v-for="(item, index) in versionList" :key="index" :value="item.id">{{item.name}}</a-select-option>
              </a-select>
              <span v-if="!isEnvLocal">
                <a-button type="primary" class="mr-10 ml-20" :disabled="!versionList.length" v-if="operateType == 'view'" @click="processAdd(2)">{{ $t('common.editor') }}</a-button>
                <a-button type="primary" @click="processAdd(1)" v-if="operateType == 'view'">{{ $t('other.addVersion') }}</a-button>
              </span>
            </a-col>
          </a-row>
        </div>
        <section>
          <a-form :model="formState" ref="formRef" layout="vertical">
            <a-row :gutter="40">
              <a-col :span="5">
                <a-form-item :label="$t('other.versionName')" :rules="processFormRule.name" name="name">
                  <a-input v-model:value.trim="formState.name" :disabled="operateType == 'view'" :maxLength="19" :placeholder="$t('common.pleaseInput')" />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item :label="$t('common.effectDate')" name="effectiveDate" :rules="processFormRule.effectiveDate">
                  <a-date-picker v-model:value="formState.effectiveDate" :disabled="operateType == 'view'" class="full-width" value-format="YYYY-MM-DD" />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item :label="$t('basicData.totalTime')" name="totalTime">
                  <a-input-number v-model:value="formState.totalTime" disabled class="full-width">
                    <template #addonAfter> {{ $t('other.seconds') }} </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item :label="$t('basicData.totalPrice')" name="totalWages">
                  <a-input-number v-model:value="formState.totalWages" disabled class="full-width">
                    <template #addonAfter> {{ $t('other.yuan') }} </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <ProcessList ref="processListRef" :styleId="moInfo.styleId" :loading="listLoading" :tableData="tableData" @workTimeChange="workTimeChange" @priceChange="priceChange" :processVersionId="processVersionId" />
        </section>
      </div>
      <div class="operate-page-btns">
        <a-button class="cancel" v-if="operateType=='view'" @click="closeTab('back')">{{ $t('other.back') }}</a-button>
        <a-space v-else>
          <a-button class="cancel" @click="closeTab('cancel')">{{$t('common.cancel')}}</a-button>
          <a-button type="primary" class="confirm" @click="onConfirm(false)">{{$t('common.ok')}}</a-button>
          <a-button type="primary" class="confirm" @click="onConfirm(true)">{{ $t('other.confirmAddRoad') }}</a-button>
        </a-space>
      </div>
    </a-spin>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { processFormRule, addList } from './processConfig'
import ProcessList from './processList.vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import axios from "@/utils/request"
import { store } from "@/store"
import { cloneDeep, uniqBy } from 'lodash'
import moment from 'moment'
import i18n from '@/locales/index' 
const { t } = i18n.global
const tabs = computed(() => {
  return store.state.setting.tabs
})
let isEnvLocal = ref(process.env.VUE_APP_CONFIG == 'local')
let loading = ref(false)
let listLoading = ref(false)
let router = useRouter()
let route = useRoute()
let moId = ref()
let moInfo = ref({})
let processVersionId = ref()
let versionList = ref([])
let processListRef = ref()
let tableData = ref([])
let operateType = ref('view')
const formState = ref({})
let formRef = ref()
const getMakeInfo = async (id) => {
  try {
    const res = await axios.getAction('/api/mo/mo/get', { id })
    moInfo.value = res.data || {}
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    moInfo.value = {}
  }
}
const getProcessList = async (id) => {
  try {
    const res = await axios.postAction('/api/mo/mo-proc/list', { moId: id })
    if (res.success) {
      versionList.value = res.data || []
      if (res.data.length && operateType.value != 'add' && !route.query.processId) {
        processVersionId.value = res.data[0].id
        getProcessDetails()
      }
    }
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    versionList.value = []
    processVersionId.value = null
  }
}
const getProcessDetails = async () => { // 工序详情
  listLoading.value = true
  try {
    const res = await axios.getAction('/api/mo/mo-proc/get', { id: processVersionId.value })
    if (res.success) {
      initPage(res.data)
    }
    listLoading.value = false
  } catch {
    listLoading.value = false
  }
}

const initPage = (data) => {
  let { name, effectiveDate, moProcDetailVOList } = data
  moProcDetailVOList.forEach(i => {
    i.processPictureUrlList && i.processPictureUrlList.forEach((el) => {
      el.status = 'done'
      el.uid = Math.random()
    })
  })
  tableData.value = moProcDetailVOList
  formState.value.name = name
  formState.value.effectiveDate = moment(effectiveDate ? effectiveDate : moment(new Date()).valueOf()).format('YYYY-MM-DD')
  formState.value.totalTime = tableData.value.reduce((prev, next) => { return prev + (next.standardSeconds || 0) }, 0).toFixed(8)
  formState.value.totalWages = tableData.value.reduce((prev, next) => { return prev + (next.labourCost || 0) }, 0).toFixed(8)
}
const workTimeChange = () => {
  formState.value.totalTime = processListRef.value.dataSource.reduce((prev, next) => { return prev + (next.standardSeconds || 0) }, 0).toFixed(8)
}
const priceChange = () => {
  formState.value.totalWages = processListRef.value.dataSource.reduce((prev, next) => { return prev + (next.labourCost || 0) }, 0).toFixed(8)
}
const queryParams = () => {
  let list = cloneDeep(processListRef.value.dataSource)
  list.forEach(i => {
    i.moId = moId.value
  })
  let { name, effectiveDate } = formState.value
  let params = {
    id: operateType.value == 'edit' ? processVersionId.value : null,
    effectiveDate: moment(effectiveDate).valueOf(),
    name,
    moId: moId.value,
    moProcDetailVOList: list
  }
  return params
}
const onConfirm = async (goRoute) => {
  try {
    await formRef.value.validateFields()
    await processListRef.value.listFormRef.validateFields()
    let list = processListRef.value.dataSource
    if (list.some(i => i.section != t('components.dg'))) {
      message.warning(t('other.sectionOnlySelectHang'))
      return
    }
    //  唯一值校验
    let isUniq = ['sortField', 'processNo', 'name', 'processCode'].some(i => uniqBy(list, i).length != list.length)
    if (isUniq) {
      message.warning(t('other.ruleFourOnly'))
      return
    }
    loading.value = true
    await sendInfo(goRoute)
    loading.value = false
  } catch {
    loading.value = false
  }
}
const sendInfo = async (goRoute) => {
  loading.value = true
  let params = queryParams()
  let url = operateType.value == 'edit' ? '/api/mo/mo-proc/edit' : '/api/mo/mo-proc/save'
  const res = await axios.postAction(url, params)

  if (res.success) {
    message.success(res.msg || t('common.doSuccess'))
    await closeTab('confirm', goRoute)
  }
}
const refreshTab = async (isAdd) => {
  let path = isAdd ? '/makeManage/makeProcess/add' : '/makeManage/makeProcess/edit'
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => ![path].includes(i.path))
  await store.commit('updateState', { tabs: changeTabs })
}
const processAdd = async (values) => {
  await refreshTab(values == 1)
  router.push(values == 1 ? {
    path: '/makeManage/makeProcess/add',
    query: { id: moId.value }
  } : {
    path: '/makeManage/makeProcess/edit',
    query: { id: moId.value, processId: processVersionId.value }
  })
}
const closeTab = async (type, goRoute) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (goRoute) {
      return !['/makeManage/routeChart/add'].includes(i.path)
    } else {
      if (type == 'confirm') {
        return !['/makeManage/makeProcess/details', route.path].includes(i.path)
      } else {
        return i.path !== route.path
      }
    }

  })
  await store.commit('updateState', { tabs: changeTabs })
  if (goRoute) {
    await router.replace({ path: '/makeManage/routeChart/add', query: { id: moId.value } })
  } else {
    type != 'back' ? await router.replace({ path: '/makeManage/makeProcess/details', query: { id: moId.value } }) : await router.replace({ path: '/makeManage/makeProcess' })
  }

}
const initAddPage = () => {
  let list = cloneDeep(addList)
  list[0].moId = route.query.id
  processVersionId.value = undefined
  initPage({ moProcDetailVOList: list })
}
onMounted(async () => {
  loading.value = true
  try {
    moId.value = route.query.id
    operateType.value = route.path == '/makeManage/makeProcess/add' ? 'add' : route.path == '/makeManage/makeProcess/edit' ? 'edit' : 'view'
    await getMakeInfo(moId.value)
    if (operateType.value != 'add') await getProcessList(moId.value)
    if (operateType.value == 'add') initAddPage()
    if (route.query.processId) {
      processVersionId.value = route.query.processId
      getProcessDetails()
    }
    loading.value = false
  } catch {
    loading.value = false
  }
})
</script>